package core

import (
	"fmt"
	"sync"
)

// AOI格子模块
type Grid struct {
	GID           int          // ID
	MinX          int          // 格子左边界坐标
	MaxX          int          // 格子右边界坐标
	MinY          int          // 格子上边界坐标
	MaxY          int          // 格子下边界坐标
	PlayerIDs     map[int]bool // 存在玩家集合
	PlayerIDsLock sync.RWMutex // 集合锁
}

// 初始化格子模块
func NewGrid(gID, minX, maxX, minY, maxY int) *Grid {
	return &Grid{
		GID:       gID,
		MinX:      minX,
		MaxX:      maxX,
		MinY:      minY,
		MaxY:      maxY,
		PlayerIDs: make(map[int]bool),
	}
}

// 添加玩家
func (g *Grid) Add(playerID int) {
	g.PlayerIDsLock.Lock()
	defer g.PlayerIDsLock.Unlock()
	g.PlayerIDs[playerID] = true
}

// 删除玩家
func (g *Grid) Remove(playerID int) {
	g.PlayerIDsLock.Lock()
	defer g.PlayerIDsLock.Unlock()
	delete(g.PlayerIDs, playerID)
}

// 返回PlayIDs切片
func (g *Grid) GetPlayerIDs() (playIDs []int) {
	g.PlayerIDsLock.RLock()
	defer g.PlayerIDsLock.RUnlock()
	playIDs = make([]int, 0, len(g.PlayerIDs))
	for k := range g.PlayerIDs {
		playIDs = append(playIDs, k)
	}
	return playIDs
}

// 调试-打印格子信息, 调用String接口, 修改fmt.Println输出的值
func (g *Grid) String() string {
	return fmt.Sprintf("[Grid]ID: %d, MinX: %d, MaxX: %d, MinY: %d, MaxY: %d, playerIDs: %v\n",
		g.GID, g.MinX, g.MaxX, g.MinY, g.MaxY, g.PlayerIDs)
}
